﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using XKPlatform.Common;
using XKPlatform.Common.Helpers;
using XKPlatform.IService.ISysService;

namespace XKPlatform.Service.SysService
{
    public class ImportTableDataService : IImportTableDataService
    {
        private readonly IConfiguration _configuration;
        public ImportTableDataService(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        /// <summary>
        /// 返回datatable和错误信息给开发者扩展开发
        /// </summary>
        /// <param name="formFile"></param>
        /// <param name="tempNum"></param>
        /// <returns></returns>
        public (string, string, DataTable, bool, IList<string>) GetImportDataTable(IFormFile formFile, string tempNum)
        {
            (string, string, DataTable, bool, IList<string>) items = ImportTableDataHelper.ImportData(formFile, tempNum);

            return items;
        }

        public (int, IList<string>) ImportData(IFormFile formFile, string tempNum)
        {
            (string, string, DataTable, bool, IList<string>) items = ImportTableDataHelper.ImportData(formFile, tempNum);
            string tableName = items.Item1;
            string dbName = items.Item2;
            DataTable table = items.Item3;
            bool isSave = items.Item4;
            IList<string> message = items.Item5;

            if (isSave)
            {
                string connectionStr = HttpContextCore.ConnectionStrings;

               
                string sql = string.Format("SELECT sdm.DataSourceColumn,sdm.TableName,sdm.TableColumn,sdm.RegRule,sdm.DataType,sdm.IsAllowNull,sdc.DbName FROM  sysDataMap sdm inner join sysDbConnection sdc on sdm.DBId  = sdc.Id WHERE sdm.TempNum = '{0}'", tempNum);
                DataSet dataMaps = SqlHelper.Query(sql);
                List<string> list = new List<string>();
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    for (int j = 0; j < dataMaps.Tables[0].Rows.Count; j++)
                    {
                        if (dataMaps.Tables[0].Rows[j]["TableColumn"].ToString() == table.Columns[i].ToString())
                        {
                            list.Add(table.Columns[i].ToString());
                        }
                    }

                }

                DataTable newTable = table.DefaultView.ToTable(false, list.ToArray());

                int count = SqlHelper.BatchInsert(newTable, tableName, newTable.Rows.Count, connectionStr);
                return (count, message);
            }
            else
            {
                return (0, message);
            }
        }
    }
}
